import axios from "axios";
import {nanoid} from "nanoid";
import alfy from "alfy";

// 获取输入的腾讯会议邀请内容或邀请码
let meet_id = process.argv[2]
if (!meet_id) {
	alfy.error('请输入腾讯会议邀请码或邀请内容')
	process.exit(1)
}


// 通过正则表达式获取会议id
const meet_id_re = [
	/([0-9]{3}[ -]?){3,}/,
	/([0-9]{9,})/,
]
let meet_id_match
for (const regExp of meet_id_re) {
	meet_id_match = meet_id.match(regExp)
	if (meet_id_match) {
		break
	}
}
if (!meet_id_match) {
	alfy.error('请输入正确的腾讯会议邀请内容或邀请码')
	process.exit(1)
}

meet_id = meet_id_match[0]


// 发起launch id 创建
const launchId = nanoid()

const data = JSON.stringify({
	"id": launchId
});
// url 参数
const urlParams = {
	c_instance_id: '',
	c_os_model: 'web',
	c_os: 'web',
	c_nonce: nanoid(),
	c_os_version: 'Mozilla%252F5.0%2520(Macintosh%253B%2520Intel%2520Mac%2520OS%2520X%252010_15_7)%2520AppleWebKit%252F537.36%2520(KHTML%252C%2520like%2520Gecko)%2520Chrome%252F138.0.0.0%2520Safari%252F537.36',
	c_timestamp: Date.now(),
	c_app_id: '',
	c_account_corp_id: '',
	c_app_uid: '',
	c_platform: '0',
	c_token: '',
	c_app_version: '',
	platform: 'Web',
	app_id: ''
}

const urlParamsString = Object.entries(urlParams)
							  .map(([key, value]) => `${key}=${value}`)
							  .join('&')
// 拼接请求体
const config = {
	method: 'post',
	url: `https://meeting.tencent.com/wemeet-webapi/v2/wemeet/service/create-launch-id?${urlParamsString}`,
	headers: {
		'content-type': 'application/json'
	},
	data: data
};

// 发起请求
axios(config)
	.then((response) => {
		const result = {
			variables: {
				launchId: launchId,
				meetId: meet_id.replaceAll('-', '').replaceAll(' ', '')
			}
		}

		alfy.output([
			{
				title: '开始会议',
				subtitle: '点击快速进入会议',
				arg: launchId,
				variables: result.variables
			}
		])
	})
	.catch((error) => {
		console.log(error.message)
	});
